package com.example.chenjian.myapplication;

import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by adi on 2016/12/25.
 */

public class WomenRegionGoods {
    private static int onePageNum = 30;

    private static int currentIndex = 0;
    private static List<GoodsItem> goodsItems = new ArrayList<GoodsItem>();

    public static void Init() {
        String rootDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        String path = rootDir + "/women.csv";

        try{
            File file = new File(path);
            if (file.exists() == false)
            {
                Log.w("EasyShopping", path + " is not exist!" );
                return;
            }

            InputStream instream = new FileInputStream(file);
            if (null != instream) {
                InputStreamReader inputReader = new InputStreamReader(instream);
                BufferedReader buffReader = new BufferedReader(inputReader);

                String line;
                while((line = buffReader.readLine()) != null){
                    GoodsItem goodsItem = parseGoodsItem(line);
                    if (null == goodsItem)
                        continue;
                    goodsItems.add(goodsItem);
                }
                instream.close();
            }

        }catch (Exception e){
            Log.w("EasyShopping", e.toString());
        }
    }


    private static GoodsItem parseGoodsItem(String line){
        String[] data = line.split(",");
        if(data.length != 5) {
            return null;
        }

        float price = Float.parseFloat(data[2]);
        GoodsItem goods = new GoodsItem(data[0], data[1], price, data[3], data[4]);
        return goods;
    }

    public static ArrayList<GoodsItem> GetGoodsItem(int index) {
        int lastNum = goodsItems.size() - index * onePageNum;
        if(lastNum <= 0) {
            return null;
        }

        int num = lastNum < onePageNum ? lastNum : onePageNum;
        List<GoodsItem> subList = goodsItems.subList(index * onePageNum, index * onePageNum + num);
        ArrayList<GoodsItem> items = new ArrayList<GoodsItem>(subList);
        return items;
    }

}
